/*
 * @Description: file write stream open queue 文件流开启队列
 * @Autor: HuiSir<github.com/huisir001>
 * @Date: 2022-07-29 10:44:54
 * @LastEditTime: 2022-07-29 13:02:19
 */
const fs = require('fs')

// Avoid the occurrence of `too many open files`error report

module.exports = () => {
    // Closure opens an array queue
    const Queue = [], maxLength = 10;
    const createWs = (path) => {
        const ws = fs.createWriteStream(path)
        ws.on('close', () => {
			console.log("--close--");
            Queue.splice(Queue.findIndex(item => item.path == ws.path), 1)
        })
        Queue.push(ws)
        return ws
    }

    return (path) => {
        return new Promise((resolve, reject) => {
            try {
                // Queue congestion
                if (Queue.length >= maxLength) {
                    // Blocking, waiting, judging every 300ms
                    const sleepTimer = setInterval(() => {
                        if (Queue.length < maxLength) {
							console.log("Queue.length2222==",Queue.length)
                            resolve(createWs(path))
                            clearInterval(sleepTimer)
                        }
                    }, 300)
                }
                // Number of queues less than maxLength
                else {
					console.log("Queue.length1111==",Queue.length)
                    resolve(createWs(path))
                }
            } catch (error) {
                reject(error)
            }
        })
    }
}